package com.loit.loitcommon.utils;


import com.loit.loitcommon.enums.CodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaokz
 * @date 2022/5/23
 * 编码生成工具类(redis自增)
 */
@Component
public class CodeGenerateUtil {
    /**
     * redis key
     */
    private static final String REDIS_ORDER_NUMBER_KEY_FORMAT = "telemedicine:code:%s";

    /**
     * 时间戳 线程安全
     */
    private static final DateTimeFormatter FORMAT_TO_DAY = DateTimeFormatter.ofPattern("yyyyMMdd");

    /**
     * redis 缓存
     */
    private static StringRedisTemplate stringRedisTemplate;

    /**
     * 自增数长度 默认4位
     */
    private static final String INCREMENT_FORMAT = "%06d";

    /**
     * 初始化Redis缓存
     */
    @Autowired
    public void setRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        CodeGenerateUtil.stringRedisTemplate = stringRedisTemplate;
    }

    public static String nextId(CodeEnum orderNoEnum) {
        String time = LocalDateTime.now().format(FORMAT_TO_DAY);
        // 获取自增数
        Long incr = incrementAndGet(orderNoEnum);
        String incrString = String.format(INCREMENT_FORMAT, incr);
        return orderNoEnum.getCode().concat(time).concat(incrString);
    }

    private static Long incrementAndGet(CodeEnum orderNoEnum) {
        // 加1
        Long counter = CodeGenerateUtil.stringRedisTemplate.opsForValue()
                .increment(getRedisOrderNumberKey(orderNoEnum), 1L);
        // 当计数器等于1的时候，设置过期时间为离第二天0点的时间差
        if (Long.valueOf(1L).equals(counter)) {
            // 获取当前时间和24点的秒数
            long timeout = betweenNowToLastSecond();
            CodeGenerateUtil.stringRedisTemplate
                    .expire(getRedisOrderNumberKey(orderNoEnum), timeout, TimeUnit.SECONDS);
        }
        return counter;
    }

    private static String getRedisOrderNumberKey(CodeEnum orderNoEnum) {
        return String.format(REDIS_ORDER_NUMBER_KEY_FORMAT, orderNoEnum.getIncrementKey());
    }

    /**
     * 计算当前时间到当天24点的差值
     *
     * @return 差值
     */
    private static long betweenNowToLastSecond() {
        LocalDateTime now = LocalDateTime.now();
        // 加一天
        LocalDateTime tomorrow = now.plusDays(1);
        LocalDateTime lastSecond = LocalDateTime.of(tomorrow.getYear(),
                tomorrow.getMonth(),
                tomorrow.getDayOfMonth(),
                0,
                0,
                0,
                1);
        return ChronoUnit.SECONDS.between(now, lastSecond);
    }
}
